package com.yisu.expressway.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.will.network.images.round.CircleImageView;
import com.yisu.expressway.BuildConfig;
import com.yisu.expressway.R;
import com.yisu.expressway.application.ExApplication;
import com.yisu.expressway.login.LoginManager;
import com.yisu.expressway.model.UserProfile;
import com.yisu.expressway.model.VersionControl;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.ui.MultiButtonDialog;
import com.yisu.expressway.ui.UpdateDialog;
import com.yisu.expressway.userprofile_setting.UpdateProfileEvent;
import com.yisu.expressway.utils.DataCleanManager;
import com.yisu.expressway.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

public class SettingActivity extends BaseActivity {

    @Bind(R.id.btn_exit)
    protected Button mBtn_Exit;
    @Bind(R.id.tv_version)
    protected TextView mTv_version;
    @Bind(R.id.iv_avatar)
    protected CircleImageView mIv_avatar;

    private UpdateDialog mUpdateDlg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        init();
    }

    private void init(){
        setTitle(R.string.setting);

        String versionTitle = getResources().getString(R.string.app_version);
        mTv_version.setText(String.format(versionTitle,BuildConfig.VERSION_NAME));

        UserProfile user = LoginManager.getUser();
        if(user != null) {
            Glide.with(ExApplication.getInstance().getApplicationContext())
                    .load(user.avatarUrl)
                    .asBitmap()
                    .placeholder(R.drawable.ic_default_avatar)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .into(mIv_avatar);
        }

        if(!LoginManager.isLoggedIn()){
            mBtn_Exit.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.tv_update_check,R.id.tv_clear_cache,R.id.tv_protocol})
    public void itemClick(TextView view){
        switch (view.getId()){
            case R.id.tv_update_check:
                checkAppVersion();
                break;
            case R.id.tv_clear_cache:
                showLoading();
                DataCleanManager.cleanInternalCache(ExApplication.getInstance().getApplicationContext());
                dismissLoading();
                ToastUtil.displayShortToastMsg(SettingActivity.this,R.string.clear_cache_success);
                break;
            case R.id.tv_protocol:
                break;
            default:
                break;
        }
    }

    @OnClick(R.id.btn_exit)
    public void doExit(){
        final MultiButtonDialog multiButtonDialog = new MultiButtonDialog(this);
        multiButtonDialog.show();
        multiButtonDialog.setContentText(R.string.login_out_warning);
        multiButtonDialog.setPositiveClickListener(new MultiButtonDialog.PositiveClickListener() {
            @Override
            public void onPositiveClick(String inputContent) {

                multiButtonDialog.dismiss();
                LoginManager.onLogout();
                mBtn_Exit.setVisibility(View.GONE);
                mIv_avatar.setImageResource(R.drawable.ic_default_avatar);

                ApiClientHelper.getApi(ApiSetting.logout(), new TypeToken<Object>() {
                        },
                        new Response.Listener<ApiResult<Object>>() {
                            @Override
                            public void onResponse(final ApiResult<Object> result) {

                                if (!result.success) {
                                    return;
                                }

                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                            }
                        }, this);
            }
        });

    }

    /**
     * 检查更新
     */
    private void checkAppVersion(){
        Map<String, Object> params = new HashMap();
        params.put("platformType", 1);
        params.put("currentVersion", BuildConfig.VERSION_CODE);
        ApiClientHelper.postApi(ApiSetting.checkVersion(), new TypeToken<VersionControl>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<VersionControl>>() {
            @Override
            public void onResponse(ApiResult<VersionControl> result) {
                if (!result.success) {
                    ToastUtil.displayLongToastMsg(SettingActivity.this, result.getMsg());
                    return;
                }


                VersionControl updateInfo = result.getResult();

                if(updateInfo == null || updateInfo.getVersionNumber() <= BuildConfig.VERSION_CODE){
                    ToastUtil.displayShortToastMsg(SettingActivity.this,R.string.no_version_update);
                    return;
                }

                if(mUpdateDlg != null) {
                    mUpdateDlg.clean();
                    mUpdateDlg = null;
                }

                mUpdateDlg = UpdateDialog.newInstance();
                mUpdateDlg.show(SettingActivity.this, updateInfo);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.displayShortToastMsg(SettingActivity.this, volleyError.getMessage());
            }
        }, this);
    }
}
